<template>
  <div class="product-list">
    <div class="search-bar">
      <el-input
          v-model="searchKeyword"
          placeholder="搜索商品名称或描述"
          class="search-input"
          @keyup.enter="handleSearch"
      >
        <template #append>
          <el-button @click="handleSearch">
            <el-icon><Search /></el-icon>
          </el-button>
        </template>
      </el-input>

      <el-select v-model="selectedType" placeholder="商品类型" @change="handleTypeChange" clearable>
        <el-option label="全部" value="" />
        <el-option label="电子产品" value="ELECTRONICS" />
        <el-option label="服装" value="CLOTHING" />
        <el-option label="食品" value="FOOD" />
        <el-option label="图书" value="BOOKS" />
        <el-option label="家居" value="HOME" />
        <el-option label="运动" value="SPORTS" />
        <el-option label="美妆" value="BEAUTY" />
        <el-option label="其他" value="OTHER" />
      </el-select>

      <el-input-number
          v-model="minPrice"
          placeholder="最低价"
          :min="0"
          :precision="2"
          :step="100"
          @change="handlePriceChange"
          style="width: 120px"
      />
      <span>-</span>
      <el-input-number
          v-model="maxPrice"
          placeholder="最高价"
          :min="0"
          :precision="2"
          :step="100"
          @change="handlePriceChange"
          style="width: 120px"
      />

      <el-button type="primary" @click="handleSearch">搜索</el-button>
      <el-button @click="resetSearch">重置</el-button>
    </div>

    <el-row :gutter="20" class="product-grid">
      <el-col :span="6" v-for="product in products" :key="product.id">
        <el-card :body-style="{ padding: '0px' }" class="product-card">
          <div class="product-badge" v-if="product.recommended">推荐</div>
          <img :src="getImageUrl(product.imageUrl)" class="product-image" />
          <div class="product-info" @click="goToDetail(product.id)">
            <h3>{{ product.name }}</h3>
            <p class="price">¥{{ product.price }}
              <span v-if="product.discountType === 'BIRTHDAY'" style="color:#e67e22;font-weight:bold;margin-left:8px;">
                生日特权价：¥{{ product.birthdayPrice }}
                <el-tag type="success" size="small">8折+积分翻倍</el-tag>
              </span>
              <span v-else-if="product.discountType === 'MEMBER'" style="color:#409eff;font-weight:bold;margin-left:8px;">
                会员价：¥{{ product.memberPrice }}
                <el-tag type="info" size="small">{{ (product.discountRate * 100).toFixed(0) }}%</el-tag>
              </span>
            </p>
            <p class="points">积分: {{ product.productPoints }}</p>
            <p class="description">{{ product.description }}</p>
            <div class="product-footer">
              <el-button type="primary" @click.stop="handleBuy(product)">立即购买</el-button>
              <el-button @click.stop="handleAddToCart(product)">加入购物车</el-button>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-empty v-if="products.length === 0" description="暂无商品" />

    <el-pagination
        v-if="total > 0"
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[12, 24, 36, 48]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        class="pagination"
    />

    <el-dialog v-model="buyDialogVisible" title="确认订单" width="500px">
      <el-form :model="orderForm" label-width="100px">
        <el-form-item label="商品信息">
          <div v-if="currentProduct">
            <p>{{ currentProduct.name }}</p>
            <p>价格: ¥{{ currentProduct.price }}</p>
            <p>积分: {{ currentProduct.productPoints }}</p>
          </div>
        </el-form-item>
        <el-form-item label="购买用户">
          <el-input v-model="currentUser.username" disabled />
        </el-form-item>
        <el-form-item label="购买数量">
          <el-input-number v-model="orderForm.quantity" :min="1" :max="currentProduct?.stock || 1" />
        </el-form-item>
        <el-form-item label="收货地址">
          <el-input v-model="orderForm.address" />
        </el-form-item>
        <el-form-item label="联系方式">
          <el-input v-model="orderForm.contactPhone" />
        </el-form-item>
        <el-form-item label="支付方式">
          <el-select v-model="orderForm.paymentMethod">
            <el-option label="支付宝" value="ALIPAY" />
            <el-option label="微信支付" value="WECHAT" />
            <el-option label="信用卡" value="CREDIT_CARD" />
            <el-option label="借记卡" value="DEBIT_CARD" />
            <el-option label="现金" value="CASH" />
            <el-option label="银行转账" value="BANK_TRANSFER" />
          </el-select>
        </el-form-item>
        <el-form-item label="运送方式">
          <el-select v-model="orderForm.shippingMethod">
            <el-option label="快递" value="EXPRESS" />
            <el-option label="标准配送" value="STANDARD" />
            <el-option label="自提" value="PICKUP" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="orderForm.remarks" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="buyDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitOrder" :loading="submitting">
            确认下单
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { getRecommendedProducts, getProductsByType, searchProducts, getProductList } from '@/api/product'
import { createOrder } from '@/api/order'
import { addToCart } from '@/api/cart'
import { useUserStore } from '@/stores/user'
import { useRouter, useRoute } from 'vue-router'

const products = ref([])
const searchKeyword = ref('')
const selectedType = ref('')
const minPrice = ref(0)
const maxPrice = ref(0)
const buyDialogVisible = ref(false)
const submitting = ref(false)
const currentProduct = ref(null)
const currentUser = ref({})
const userStore = useUserStore()
const router = useRouter()
const route = useRoute()
const currentPage = ref(1)
const pageSize = ref(12)
const total = ref(0)

const orderForm = ref({
  quantity: 1,
  address: '',
  contactPhone: '',
  paymentMethod: '',
  shippingMethod: '',
  remarks: ''
})

// 从URL参数初始化搜索条件
const initSearchParams = () => {
  const query = route.query
  if (query.name) searchKeyword.value = query.name
  if (query.type) selectedType.value = query.type
  if (query.minPrice) minPrice.value = Number(query.minPrice)
  if (query.maxPrice) maxPrice.value = Number(query.maxPrice)
  if (query.page) currentPage.value = Number(query.page)
  if (query.size) pageSize.value = Number(query.size)
}

// 更新URL参数
const updateUrlParams = () => {
  const query = {
    name: searchKeyword.value || undefined,
    type: selectedType.value || undefined,
    minPrice: minPrice.value || undefined,
    maxPrice: maxPrice.value || undefined,
    page: currentPage.value > 1 ? currentPage.value : undefined,
    size: pageSize.value !== 12 ? pageSize.value : undefined
  }

  // 移除undefined的参数
  Object.keys(query).forEach(key => {
    if (query[key] === undefined) {
      delete query[key]
    }
  })

  router.replace({ query })
}

// 监听搜索条件变化
watch([searchKeyword, selectedType, minPrice, maxPrice, currentPage, pageSize], () => {
  updateUrlParams()
})

onMounted(async () => {
  initSearchParams()
  await loadProducts()
  // 获取当前用户信息
  if (userStore.isLoggedIn) {
    currentUser.value = userStore.userInfo
  }
})

const loadProducts = async () => {
  try {
    const params = {
      page: 1,
      size: 20
    }
    const res = await getProductList(params)
    products.value = res.data.records || res.data
  } catch (error) {
    console.error(error)
    ElMessage.error('加载商品失败')
  }
}

const handleSearch = async () => {
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      name: searchKeyword.value,
      type: selectedType.value,
      minPrice: minPrice.value || undefined,
      maxPrice: maxPrice.value || undefined
    }

    const res = await getProductList(params)
    products.value = res.data.records || res.data
    total.value = res.data.total || 0
  } catch (error) {
    console.error(error)
    ElMessage.error('搜索失败')
  }
}

const handleTypeChange = async () => {
  await handleSearch()
}

const handlePriceChange = async () => {
  if (minPrice.value && maxPrice.value && minPrice.value > maxPrice.value) {
    ElMessage.warning('最低价不能大于最高价')
    maxPrice.value = minPrice.value
  }
  await handleSearch()
}

const resetSearch = async () => {
  searchKeyword.value = ''
  selectedType.value = ''
  minPrice.value = 0
  maxPrice.value = 0
  await loadProducts()
}

const handleBuy = (product) => {
  currentProduct.value = product
  orderForm.value.quantity = 1
  buyDialogVisible.value = true
}

const handleAddToCart = async (product) => {
  try {
    await addToCart({
      productId: product.id,
      quantity: 1,
      productName: product.name,
      price: product.price,
      image: product.image
    })
    ElMessage.success('已加入购物车')
  } catch (error) {
    console.error(error)
    ElMessage.error('加入购物车失败')
  }
}

const submitOrder = async () => {
  if (!currentProduct.value) return

  if (!orderForm.value.address || !orderForm.value.contactPhone) {
    ElMessage.warning('请填写完整的收货信息')
    return
  }

  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }

  submitting.value = true
  try {
    const orderData = {
      userId: userStore.userInfo.id,
      productId: currentProduct.value.id,
      quantity: orderForm.value.quantity,
      address: orderForm.value.address,
      contactPhone: orderForm.value.contactPhone,
      paymentMethod: orderForm.value.paymentMethod,
      shippingMethod: orderForm.value.shippingMethod,
      remarks: orderForm.value.remarks || '',
      orderStatus: 'PENDING',
      totalAmount: currentProduct.value.price * orderForm.value.quantity,
      orderPoints: currentProduct.value.productPoints * orderForm.value.quantity
    }

    await createOrder(orderData)
    ElMessage.success('下单成功')
    buyDialogVisible.value = false
    // 重新加载商品列表
    await handleSearch()
  } catch (error) {
    console.error(error)
    ElMessage.error('下单失败')
  } finally {
    submitting.value = false
  }
}

const goToDetail = (id) => {
  router.push(`/products/${id}`)
}

const handleSizeChange = (val) => {
  pageSize.value = val
  handleSearch()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  handleSearch()
}

// 处理图片URL
const getImageUrl = (url) => {
  if (!url) return defaultProductImage
  if (url.startsWith('http')) return url
  if (url.startsWith('/uploads/')) return `http://localhost:8080${url}`
  return `http://localhost:8080/uploads/${url}`
}
</script>

<style scoped>
.product-list {
  padding: 20px;
}

.search-bar {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
  align-items: center;
  flex-wrap: wrap;
}

.search-input {
  width: 300px;
}

.product-grid {
  margin-top: 20px;
}

.product-card {
  margin-bottom: 20px;
  position: relative;
  transition: all 0.3s;
}

.product-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
}

.product-badge {
  position: absolute;
  top: 10px;
  right: 10px;
  background-color: #f56c6c;
  color: white;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  z-index: 1;
}

.product-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
}

.product-info {
  padding: 14px;
}

.product-info h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
}

.price {
  color: #f56c6c;
  font-size: 20px;
  font-weight: bold;
  margin: 10px 0 5px 0;
}

.points {
  color: #67c23a;
  font-size: 14px;
  margin: 5px 0;
}

.description {
  color: #666;
  font-size: 14px;
  margin: 10px 0;
  height: 40px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.product-footer {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style> 